package com.jiang.realm;

import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jiang.sevice.IMemberService;
import com.jiang.utils.EncryptUtils;
import com.jiang.vo.Member;

@Component
public class MemberRealm extends AuthorizingRealm {

	@Autowired
	private IMemberService memberService;
	
	
	/**
	 * 进行授权认证
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		
		SimpleAuthorizationInfo authorization = new SimpleAuthorizationInfo();
		String mid = principalCollection.getPrimaryPrincipal().toString();
		Map<String,Object> map = memberService.listAuthByMember(mid);
		Set<String> roles = (Set<String>) map.get("roles");
		Set<String> perms = (Set<String>) map.get("permissions");
		authorization.setRoles(roles);
		authorization.setStringPermissions(perms);
		
		return authorization;
	}

	/**
	 * 进行身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		String mid = token.getPrincipal().toString();
		String pre_password = new String((char[])token.getCredentials());
		System.out.println(pre_password);
		// 获取验证的用户
		Member member = memberService.getById(mid);
		if(member==null){
			throw new UnknownAccountException("用户名不存在!");
		}else{
			// 判断用户名密码
			// 比较之前，进行原始密码加密比较
			String password = EncryptUtils.encry(pre_password);
			if(StringUtils.isNotBlank(member.getPassword()) && member.getPassword().equals(password)){
				return new SimpleAuthenticationInfo(mid,pre_password,"memberRealm");
			}else{
				throw new IncorrectCredentialsException("密码错误!");
			}
			
		}
	}

}
